package com.db.chat.server.history;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

/**
 * Saves and loads history to/from file
 */

public class HistoryHandler implements Closeable {
    private File file;
    private BufferedWriter writer;

    /**
     *
     * @param fileName
     * @throws HistoryException if file can not be created / written
     */
    public HistoryHandler( String fileName) throws HistoryException {
        file = new File(fileName);
        try {
            writer = new BufferedWriter(new FileWriter(file, true));
        } catch (IOException e) {
            throw new HistoryException();
        }
    }

    public void write( String text) throws HistoryWriteException{
        try {
            writer.write(text + "\n");
        } catch (IOException e) {
            throw new HistoryWriteException();
        }
    }

    /**
     *
     * @param max - number of latest messages, null means unlimited
     * @throws HistoryReadException
     */
    public  List<String> readAsList( Integer max) throws HistoryReadException {
        List<String> result = new LinkedList<String>();
        if (!file.exists()) {
            return result;
        }
        try(
            BufferedReader reader = new BufferedReader(new FileReader(file))
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (max != null && max.equals(result.size())) {
                    result.remove(0);
                }
                result.add(line);
            }
            return result;
        } catch (IOException e) {
            throw new HistoryReadException();
        }
    }

    /**
     *
     * @param max - number of latest messages, null means unlimited
     * @throws HistoryReadException
     */
    public  String readAsLine(Integer max) throws HistoryReadException {
        StringBuilder sb = new StringBuilder();
        for (String line : readAsList(max)) {
            sb.append(line).append("\n");
        }
        return sb.toString();
    }

    @Override
    public void close() throws IOException {
        writer.close();
    }
}